'''
陈超依 19377189
现代程序设计第七次作业
'''

import xlrd
from matplotlib import pyplot as plt 
import matplotlib
matplotlib.rc("font",family='YouYuan')

class NotNumError(ValueError):
    def __init__(self, year : int, industry : str, type : str, province : str):
        self.year = year
        self.industry = industry
        self.type = type
        self.province = province

class ZeroDivisionError(ValueError):
    def __init__(self, province : str):
        self.province = province

class DataAnalyse:
    def __init__(self, files : dict):
        '''输入年份为键，文件名为值的字典，以确定分析文件'''
        self.files = files
    def province_type_analyse(self, province : str, industry: str, type : str):
        '''输入地区名、产业与排放类型，输出时间为键，排放为值的字典'''
        ans = {}
        for year in self.files:
            try:
                data = xlrd.open_workbook(self.files[year])
                table = data.sheet_by_name(province)
                industrys = table.col_values(0)
                for i in range(len(industrys)):
                    if (industrys[i] == industry):
                        break
                types = table.row_values(0)
                for j in range(len(types)):
                    if (types[j] == type):
                        break
                if (table.cell_value(i, j) == ''):
                    print("year : {}\nindustry : {}\ntype : {}\nprovince : {}"\
                        .format(year, industry, type, province))
                    raise NotNumError(year, industry, type, province)
                ans[year] = table.cell_value(i, j)
            except NotNumError as NE:
                ans[NE.year] = 0
        return ans
    def year_type_analyse(self, year : int, industry : str, type : str):
        '''输入年份、产业与排放类型，输出地区名为键，排放为值的字典'''
        ans = {}
        if (year not in self.files):
            return "输入的年份未在指定的文件中"
        data = xlrd.open_workbook(self.files[year])
        table = data.sheet_by_name("Sum")
        provinces = table.col_values(0)
        for province in provinces:
            try:
                if (province != ''):
                    if (province != 'Sum-CO2'):
                        table = data.sheet_by_name(province)
                        industrys = table.col_values(0)
                        for i in range(len(industrys)):
                            if (industrys[i] == industry):
                                break
                        types = table.row_values(0)
                        for j in range(len(types)):
                            if (types[j] == type):
                                break
                        if (table.cell_value(i, j) == ''):
                            print("year : {}\nindustry : {}\ntype : {}\nprovince : {}"\
                                .format(year, industry, type, province))
                            raise NotNumError(year, industry, type, province)
                        ans[province] = table.cell_value(i, j)
            except NotNumError as NE:
                ans[NE.province] = 0
        return ans

class DataPrint:
    def year_value_lines(data : dict, title : str):
        '''输入键为年份，值为排放量的字典，绘制折线图'''
        plt.xlabel("年份")
        plt.ylabel("排放量")
        plt.title(title)
        plt.plot(list(data.keys()), list(data.values()))
        plt.xticks(range(min(list(data.keys())),max(list(data.keys())), 2))
        plt.show()
    def province_pie(data : dict, title : str):
        '''输入键为地区名，值为排放量的字典，绘制饼图'''
        plt.pie(list(data.values()), labels=(list(data.keys())))
        plt.title(title)
        plt.show()

def main():
    files = {}
    for i in range(1997, 2016, 1):
        files[i] = "E:\\Py_Programs\\week7\\data\\Province sectoral CO2 emissions %d.xlsx"%i
    dataanalyse = DataAnalyse(files)
    '''测试数据分析与展示功能'''
    print(dataanalyse.province_type_analyse("Beijing", "Total Consumption", "Raw Coal"))
    #DataPrint.year_value_lines(dataanalyse.province_type_analyse("Beijing", "Total Consumption", "Raw Coal"), "北京各年总排放")
    #print(dataanalyse.year_type_analyse(1997, "Total Consumption", "Raw Coal"))
    #DataPrint.province_pie(dataanalyse.year_type_analyse(1997, "Total Consumption", "Raw Coal"), "各地区1997年排放情况")
    '''测试ZeroDivisionError'''
    '''
    try:
        data = dataanalyse.year_type_analyse(1997, "Total Consumption", "Other Petroleum Products")
        for k in data:
            if (data[k] == 0):
                raise ZeroDivisionError(k)
    except ZeroDivisionError as ZD:
        print("province : {}".format(ZD.province))
    '''
    



if __name__ == '__main__':
    main()